package com.itfreer.file.service;

import java.io.IOException;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import com.itfreer.file.FileSegmentInfo;
import com.itfreer.utils.json.JsonUtils;

/**
 * 定义文件上传接口服务
 */
@Component
@Path("/file/objectUploadService")
public class ObjectUploadService {

	@Autowired
	private IObjectUploadService objectUpload;
	
	/**
	 * 创建文件夹
	 * 多级目录创建最后一级即可，比如dir1/dir2/dir3/，创建dir1/dir2/dir3/即可，dir1/、dir1/dir2/不需要创建
	 * @param bucketName	存储块名称
	 * @param objectName	文件夹名称
	 */
	@POST
    @Path("/createDir")
	public void createDir(@QueryParam("bucketName") String bucketName, 
			@QueryParam("objectName") String objectName){
		objectUpload.createDir(bucketName, objectName);
	}
	
	/**
	 * 上传文件流
	 * @param bucketName 	存储块名称
	 * @param objectKey		对象存储key
	 * @param content		对象流
	 * @param meta			对象元数据
	 */
	@SuppressWarnings("unchecked")
	@POST
    @Path("/putObject")
	@Produces(MediaType.APPLICATION_JSON)
	public boolean putObject(@QueryParam("bucketName") String bucketName, 
			@QueryParam("objectKey") String objectKey, 
			@QueryParam("content") String content, 
			@QueryParam("meta") String meta){
		byte[] byteArray = null;
		Map<String, String> map = null;
		try {
			map = JsonUtils.toBean(meta, Map.class);
			byteArray = JsonUtils.toBean(content, byte[].class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return objectUpload.putObject(bucketName, objectKey, byteArray, map);
	}
	
	/**
	 * 断点续传上传
	 * @param bucketName		存储块名称
	 * @param objectKey		对象存储key
	 * @param content		上传内容
	 * @param partIndex		分片大小
	 * @param meta			对象元数据
	 */
	@SuppressWarnings("unchecked")
	@POST
    @Path("/uploadFile")
	@Produces(MediaType.APPLICATION_JSON)
	public boolean uploadFile(@QueryParam("bucketName") String bucketName, 
			@QueryParam("objectKey") String objectKey, 
			@QueryParam("part") String part, 
			@QueryParam("meta") String meta){
		FileSegmentInfo fileSegmentInfo = null;
		Map<String, String> map = null;
		try {
			fileSegmentInfo = JsonUtils.toBean(part, FileSegmentInfo.class);
			map = JsonUtils.toBean(meta, Map.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return objectUpload.uploadFile(bucketName, objectKey, fileSegmentInfo, map);
	}
}
